﻿using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using PropertyChanged;
using sys_Print.DataAsset;
using sys_Print.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Shapes;
using ZXing;
using static System.Net.Mime.MediaTypeNames;

namespace sys_Print.ViewModel
{
    [AddINotifyPropertyChangedInterface]
    public class PrintViewModel
    {
        [DoNotNotify]
        private readonly IFreeSql _fsql;

        public ObservableCollection<PrintRecordList> PrintRecordLists { get; set; }
        public ObservableCollection<PrintCanvasModel> PrintCanvasModels { get; set; }
        public ObservableCollection<PrintCanvasModel> PrintBackCanvasModels { get; set; }
        public ObservableCollection<DataGridList> DataGridLists { get; set; }
        public ContentType ContentType { get; set; }
        public PrintModelType PrintModelType { get; set; }
        public double RowHeight { get; set; }


        public RelayCommand<PrintRecordList> ListViewItemClickCommand { get; private set; }
        public RelayCommand<TextBox> EnterKeyPressedSearchBar { get; private set; }
        public RelayCommand<Button> PrintButtonCommand { get; private set; }

        public PrintViewModel()
        {
            _fsql = App.FsqlDB;

            ListViewItemClickCommand = new RelayCommand<PrintRecordList>(new Action<PrintRecordList>(CommandListViewItemClick));
            EnterKeyPressedSearchBar = new RelayCommand<TextBox>(new Action<TextBox>(SearchBarEnterKeyPressed));
            PrintButtonCommand = new RelayCommand<Button>(new Action<Button>(OnPrintButton));
        }

        /// <summary>
        /// 打印
        /// </summary>
        private void OnPrintButton(Button button)
        {
            //设置打印参数
            PrintDialog printDialog = new PrintDialog();

            //选择打印


            // 获取要打印的 Border
            Border printBorder = new Border();
            printBorder = FindVisualChild<Border>(App.Current.MainWindow, "StrCanvas");

            //创建一个FixedDocument
            FixedDocument fixedDoc = new FixedDocument();
            fixedDoc.DocumentPaginator.PageSize = new Size(printBorder.Width, printBorder.Height);

            // 创建一个页面
            PageContent pageContent = new PageContent();
            fixedDoc.Pages.Add(pageContent);

            // 创建一个FixedPage，并将其添加到页面中
            FixedPage fixedPage = new FixedPage();
            ((IAddChild)pageContent).AddChild(fixedPage);

            // 创建一个VisualBrush，用于捕获Canvas的呈现
            VisualBrush visualBrush = new VisualBrush(printBorder);
            Rectangle rectangle = new Rectangle();
            rectangle.Width = printBorder.Width;
            rectangle.Height = printBorder.Height;
            rectangle.Fill = visualBrush;

            // 添加Rectangle到FixedPage
            fixedPage.Children.Add(rectangle);


            bool? result = printDialog.ShowDialog();

            if (result == true) // 如果用户点击了打印按钮
            {
                // 打印FixedDocument
                printDialog.PrintDocument(fixedDoc.DocumentPaginator, "Printing Canvas");
            }

        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="textBox"></param>
        private void SearchBarEnterKeyPressed(TextBox textBox)
        {
            // 处理按下回车键的逻辑，参数text为TextBox中的文本内容
            if (Keyboard.IsKeyDown(Key.Return))
            {
                if (textBox.Text == string.Empty && textBox.Text == "")
                {
                    PrintRecordLists?.Clear();
                    return;
                }

                List<PrintRecordList> lists = new List<PrintRecordList>();

                switch (textBox.Tag)
                {
                    case "FactoryNo":
                        lists = _fsql.Select<PrintRecordList>().Where(a => a.FactoryNo.Contains(textBox.Text)).ToList();
                        PrintRecordLists = new ObservableCollection<PrintRecordList>(lists);
                        return;
                    case "FBillNo":
                        lists = _fsql.Select<PrintRecordList>().Where(a => a.FBillNo.Contains(textBox.Text)).ToList();
                        PrintRecordLists = new ObservableCollection<PrintRecordList>(lists);
                        return;
                    case "SalesNo":
                        lists = _fsql.Select<PrintRecordList>().Where(a => a.SalesNo.Contains(textBox.Text)).ToList();
                        PrintRecordLists = new ObservableCollection<PrintRecordList>(lists);
                        return;
                    default:
                        return;

                }                
            }
        }


        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="printRecordList"></param>
        private void CommandListViewItemClick(PrintRecordList printRecordList)
        {
            if (printRecordList.DataPrintModelType != "[]")
            {
                PrintCanvasModels = JsonConvert.DeserializeObject<ObservableCollection<PrintCanvasModel>>(printRecordList.DataPrintCanvasModel);
            }

            if (printRecordList.DataPrintBackCanvasModel != "[]")
            {
                PrintCanvasModels = JsonConvert.DeserializeObject<ObservableCollection<PrintCanvasModel>>(printRecordList.DataPrintBackCanvasModel);
            }

            PrintModelType = JsonConvert.DeserializeObject<PrintModelType>(printRecordList.DataPrintModelType);

            //设置DataGrid宽度
            DemoViewModel.DataGridWidth(PrintCanvasModels);

        }


        public static T FindVisualChild<T>(DependencyObject parent, string name) where T : DependencyObject
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(parent, i);

                if (child is T element && (element as FrameworkElement)?.Name == name)
                {
                    return element;
                }

                T result = FindVisualChild<T>(child, name);

                if (result != null)
                {
                    return result;
                }
            }

            return null;
        }

    }
}
